package com.ijava.base.service.impl;


import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.ijava.base.dao.PositionDAO;
import com.ijava.base.domain.Position;
import com.ijava.base.service.PositionService;

public class PositionServiceImpl implements PositionService {
	private static final Logger logger = LoggerFactory.getLogger(PositionServiceImpl.class);
	private PositionDAO dao;

	// private DataSource dataSource;

	// public DataSource getDataSource() {
	// return dataSource;
	// }
	//
	// public void setDataSource(DataSource dataSource) {
	// this.dataSource = dataSource;
	// }

	public PositionDAO getDao() {
		return dao;
	}

	public void setDao(PositionDAO dao) {
		this.dao = dao;
	}

	public void remove(String id) throws Exception {
		dao.remove(id);
	}

	public void mutilRemove(Position position) throws Exception {
		try {
			String[] keys = position.getKeys();
			if(null == keys)
				return;
			for (int i = 0; i < keys.length; i++) {
				remove(keys[i]);
			}
		} catch (Exception e) {
			logger.error("", e);
			throw e;
		}
	}

	public void save(Position position) throws Exception {
		dao.save(position);
	}

	public void update(Position position) throws Exception {
		dao.update(position);
	}

	public void saveOrUpdate(Position position) throws Exception {
		dao.saveOrUpdate(position);
	}

	public Position get(String id) throws Exception {
		return dao.get(id);
	}

	public List findWithPaging(Position position) throws Exception {
		try {
			int firstRow = (position.getPageNo() - 1) * position.getPageSize();
			int maxRow = position.getPageSize();

			// JdbcTemplate template = new JdbcTemplate(dataSource);
			// int total =
			// template.queryForInt("SELECT COUNT(1) FROM TABLE_NAME");
			// position.setTotal(total);

			List paramList = new ArrayList();
			StringBuffer condition = new StringBuffer(" where 1 = 1 ");
			if (StringUtils.hasLength(position.getPositionCode())) {
				condition.append(" and positionCode like ?");
				paramList.add("%" + position.getPositionCode() + "%");
			}
			if (StringUtils.hasLength(position.getPositionName())) {
				condition.append(" and positionName like ?");
				paramList.add("%" + position.getPositionName() + "%");
			}
			if (StringUtils.hasLength(String.valueOf(position.getRowEnable()))) {
				condition.append(" and rowEnable = ?");
				paramList.add(position.getRowEnable());
			}

			int total = dao.find(
					"select count(*) from " + Position.class.getName()
							+ condition.toString(), paramList).size();
			position.setTotal(total);

			String queryString = "from " + Position.class.getName()
					+ condition.toString();
			return dao.findWithPaging(queryString, paramList, firstRow, maxRow);
		} catch (Exception e) {
			logger.error("", e);
			throw e;
		}
	}

}
